package top.wardyan.wbaseswt.conf.service.impl;

import top.wardyan.base.common.annotation.Service;
import top.wardyan.base.db.service.impl.BaseDetailServiceImpl;
import top.wardyan.wbaseswt.conf.model.SysTableCol;
import top.wardyan.wbaseswt.conf.service.ISysTableColService;

@Service
public class SysTableColServiceImpl extends BaseDetailServiceImpl<SysTableCol> implements ISysTableColService{

	private final String SQL_FIND = "SELECT * FROM " + getTable() + " WHERE xClassName = ? AND xTableName = ? AND xFieldName = ? limit 1";
	private final String SQL_FIND_BYINDEX = "SELECT * FROM " + getTable() + " WHERE xClassName = ? AND xTableName = ? AND sIndex = ? limit 1";
	private final String SQL_MAXINDEX = "SELECT * FROM " + getTable() + " WHERE xClassName = ? AND xTableName = ? ORDER BY dID DESC limit 1";
	private final String SQL_LIST = "SELECT * FROM " + getTable() + " WHERE xClassName = ? AND xTableName = ? ORDER BY dID ";
	private final String SQL_FINDBYSID = "SELECT * FROM " + getTable() + " WHERE sID = ? limit 1";
	private final String SQL_GETANAUTOTITLE = "SELECT xTitle FROM " + getTable() + " WHERE xField = ? GROUP BY xTitle ORDER BY COUNT(1) DESC LIMIT 1 ";

	@Override
	public SysTableCol find(String className, String tableName, String field) {
		return this.findBySQL(SQL_FIND, className, tableName, field);
	}

	@Override
	public SysTableCol find(String className, String tableName, Integer index) {
		return this.findBySQL(SQL_FIND_BYINDEX, className, tableName, index);
	}

	@Override
	public Integer maxIndex(String className, String tableName) {
		SysTableCol c = this.findBySQL(SQL_MAXINDEX, className, tableName);
		Integer rs = 1;
		if(c != null) {
			Integer x = c.getSIndex();
			if(x != null) {
				rs = x + 1;
			}
		}
		return rs;
	}

	@Override
	public java.util.List<SysTableCol> list(String className, String tableName) {
		return this.List(SQL_LIST, className, tableName);
	}

	@Override
	public SysTableCol find(Integer sID) {
		return this.findBySql(SQL_FINDBYSID, sID);
	}

	@Override
	public String getAnAutoTitle(String xField) {
		String rs = xField;
		SysTableCol tc = this.findBySql(SQL_GETANAUTOTITLE, xField);
		if(tc != null) {
			rs = tc.getXField();
		}
		return rs;
	}


}
